/*
 * Copyright 2013 Glassy Cinema.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package hu.glassy.web.panel.movie.edit;

import hu.glassy.core.model.Movie;
import hu.glassy.core.service.MovieService;
import hu.glassy.web.GlassyApplication;
import hu.glassy.web.panel.common.CustomPanel;
import java.io.File;
import java.io.IOException;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.upload.FileUpload;
import org.apache.wicket.markup.html.form.upload.FileUploadField;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.file.Files;
import org.apache.wicket.util.file.Folder;
import org.apache.wicket.util.lang.Bytes;

/**
 *
 * @author Alexander Molnár <molnar.alexander@sonrisa.hu>
 */
public final class MoviePictureEditPanel extends CustomPanel<Movie>
{

  @SpringBean
  private MovieService movieService;

  public MoviePictureEditPanel(String id, IModel<Movie> model)
  {
    super(id, model);

    final FileUploadForm simpleUploadForm = new FileUploadForm("simpleUpload");
    simpleUploadForm.setModel(model);
    add(simpleUploadForm);
  }

  /**
   * Form for uploads.
   */
  private class FileUploadForm extends Form<Movie>
  {

    FileUploadField fileUploadField;

    /**
     * Construct.
     *
     * @param name
     *             Component name
     */
    public FileUploadForm(String name)
    {
      super(name);

      // TODO: http://www.mail-archive.com/wicket-user@lists.sourceforge.net/msg17213.html
      // set this form to multipart mode (allways needed for uploads!)
      setMultiPart(true);

      // Add one file input field
      add(fileUploadField = new FileUploadField("fileInput"));

      // Set maximum size to 100K for demo purposes
      setMaxSize(Bytes.kilobytes(1024));
    }

    /**
     * @see org.apache.wicket.markup.html.form.Form#onSubmit()
     */
    @Override
    protected void onSubmit()
    {
      final FileUpload upload = fileUploadField.getFileUpload();
      if (upload != null)
      {
        // Create a new file
        File newFile = new File(getUploadFolder(), upload.getClientFileName());

        // Check new file, delete if it already existed
        removeFile(newFile);
        try
        {
          // Save to new file
          newFile.createNewFile();
          upload.writeTo(newFile);

          logger.info("New poster image has been saved to :" + upload.getClientFileName());
          movieService.changePosterImage(this.getModelObject(), upload.getClientFileName());

          info("saved file: " + upload.getClientFileName());
        }
        catch (IOException e)
        {
          throw new IllegalStateException("Unable to write file", e);
        }
      }
    }

    /**
     * Check whether the file allready exists, and if so, try to delete it.
     *
     * @param newFile the file to check
     */
    private void removeFile(File newFile)
    {
      if (newFile.exists())
      {
        // Try to delete the file
        if (!Files.remove(newFile))
        {
          throw new IllegalStateException("Unable to overwrite file: " + newFile.getAbsolutePath());
        }
      }
    }

    private Folder getUploadFolder()
    {

      return GlassyApplication.get().getImageUploadFolder();
    }
  }
}
